package com.acme.gprs.client;

//import java.io.BufferedReader;
import java.io.IOException;
//import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.acme.gprs.server.GPRSAppliancesServer;

public class GPRSApplianceClientTest implements Runnable{
	private Socket connection;
	//private BufferedReader in;
	private PrintStream out;
	
	public GPRSApplianceClientTest(){
		try {
			connection = new Socket("localhost",GPRSAppliancesServer.GPRS_LISTENER_PORT);
			//in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			out = new PrintStream(this.connection.getOutputStream());
			Thread clientThread = new Thread(this);
			clientThread.start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void disconnect(){
		if(connection.isConnected()){
			try {
				System.out.println("Disconnecting");
				connection.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Override
	public void run() {
		try {
			/*
			System.out.println("Blocking for a message...");
			while((incomingCommand=in.readLine()) != null){
				System.out.println("Command received: " + incomingCommand);
				System.out.println("Blocking for a message...");
			}
			*/
			while(true){
				Thread.sleep(1000*5);
				out.println("heartbeat");
				if(out.checkError()){
					break;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			disconnect();
		}
		
		
	}
	
	public static void main(String[] args) {
		new GPRSApplianceClientTest();
	}

}
